package com.woniuxy.yoga.commons.web.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    //创建订单死信队列的交换机
    @Bean
    public DirectExchange serviceDelayExchange(){
        //创建交换机用于将死信通过交换机转发到其他队列中
        return new DirectExchange("oder-delay-ex");
    }

    //创建订单死信队列
    @Bean
    public Queue delayOrderQueue(){
        Map<String, Object> params = new HashMap<>();
        //定义该队列中消息的生存时间 单位毫秒 生存时间最终对应业务的延迟执行时间
        params.put("x-message-ttl",15*60*1000);
        //x-dead-letter-exchange 属性用于声明死信转发到的交换机
        params.put("x-dead-letter-exchange","order-delay-ex");
        //x-dead-letter-routing-key 声明了这些死信在转发时携带的路由键名称
        params.put("x-dead-letter-routing-key","order");
        return new Queue("order-delay",true,false,false,params);
    }

    //创建交换机
    @Bean
    public DirectExchange errorEx(){
        return new DirectExchange("error-ex");
    }

    //创建队列
    @Bean
    public Queue errorQueue(){
        return new Queue("error-queue",true,false,false,null);
    }

    //绑定交换机和队列
    @Bean
    public Binding bindErrorQueue(){
        return BindingBuilder.bind(errorQueue()).to(errorEx()).with("error");
    }

    //消费者报异常次数限制和数据回复
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        // 需要配置交换机和绑定键
        return new RepublishMessageRecoverer(rabbitTemplate, "error-ex", "error");
    }
}
